package com.settlement.system.controller;

import com.settlement.system.csv.CsvExportBuilder;
import com.settlement.system.csv.CsvExportUtil;
import com.settlement.system.common.enums.ExcelFileType;
import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.BasePager;
import com.settlement.system.model.entity.common.TblNcVurcherDetailPlus;
import com.settlement.system.model.entity.common.TblNcVurcherDetailPlusExportData;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblNcVurcherDetailPlusService;
import com.settlement.system.service.csv.DateSpiltCsvDatas;
import com.settlement.system.common.util.common.FasUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * NC凭证明细_优化 前端控制器
 * @author xiaochuan
 * @since 2021-01-20
 */

@Slf4j
@Api(tags = "NC凭证明细_优化",description = "NC凭证明细_优化")
@RestController
@RequestMapping("/nc/vurcher-detail-plus")
public class TblNcVurcherDetailPlusController extends ExcelController<TblNcVurcherDetailPlus> {

    @Value("${system.export-root.path}")
    private String exportRootPath;

    @Resource
    private ITblNcVurcherDetailPlusService tblNcVurcherDetailPlusService;

    @Override
    public IBaseService init() {
        return tblNcVurcherDetailPlusService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblNcVurcherDetailPlus.class;
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        result.put("foot",tblNcVurcherDetailPlusService.getFoot(model));
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        model.put("orderByField",
                        "v.sort asc," +
                        "concat(d.record_account_project , v.voucher_type) asc," +
                        "v.sort asc," +
                        "LENGTH(v.voucher_type) asc,nc_shop_name asc," +
                        "if(origin_coin_borrower_amount=0,0,1) desc,if(target_coin_borrower_amount=0,0,1) desc,if(origin_coin_loan_amount=0,0,1) desc,if(target_coin_loan_amount=0,0,1) desc, d.id");
        FasUtil.formatInQueryCondition(model,"editorName","companyNo","summaryId","vurcherNumber");
        super.setParamsModel(model);
    }

    @Override
    public String getSheetName() {
        return "NC凭明细";
    }

    @Override
    public void processModel(BasePager<Map<String,Object>> model) {
        model.setOrderByField(
                        "v.sort asc," +
                        "concat(d.record_account_project , v.voucher_type) asc," +
                        "v.sort asc," +
                        "LENGTH(v.voucher_type) asc,nc_shop_name asc," +
                        "if(origin_coin_borrower_amount=0,0,1) desc,if(target_coin_borrower_amount=0,0,1) desc,if(origin_coin_loan_amount=0,0,1) desc,if(target_coin_loan_amount=0,0,1) desc, d.id");
        super.processModel(model);
    }

    @ApiOperation("撤销NC")
    @RequestMapping(value = "revoke", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse revokeNc(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            FasUtil.formatInQueryCondition(model,"editorName","companyNo","summaryId","vurcherNumber");
            String message = tblNcVurcherDetailPlusService.revokeNc(model);
            if (StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @ApiOperation("校验推送NC数据")
    @PostMapping("checkPush")
    @ResponseBody
    public ObjectDataResponse checkPush(@RequestBody Map<String, Object> params) {
        try {
            FasUtil.formatInQueryCondition(params, "editorName", "companyNo", "summaryId","vurcherNumber");
            String result = tblNcVurcherDetailPlusService.checkPush(params);
            if (StringUtils.equalsAny(result, "1", "3")) {
                return new ObjectDataResponse(result,ReturnStatusEnum.REQUEST_SUCCESS);
            }else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), result);
            }
        } catch (Exception ex) {
            log.info("校验推送NC数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE);
        }
    }


    @ApiOperation("推送NC")
    @PostMapping("pushNc")
    @ResponseBody
    public ObjectDataResponse pushNc(@RequestBody Map<String, Object> params) {
        try {
            FasUtil.formatInQueryCondition(params, "editorName", "companyNo", "summaryId","vurcherNumber");
            String result = tblNcVurcherDetailPlusService.pushNc(params);
            if (StringUtils.isEmpty(result)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            }else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), result);
            }
        } catch (Exception ex) {
            log.info("推送NC数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE);
        }
    }

    @ApiOperation("撤销推送NC")
    @PostMapping("deletePushNc")
    @ResponseBody
    public ObjectDataResponse deletePushNc(@RequestBody Map<String, Object> params) {
        try {

            FasUtil.formatInQueryCondition(params, "editorName", "companyNo", "summaryId","vurcherNumber");
            String result = tblNcVurcherDetailPlusService.deletePushNc(params);
            if (StringUtils.isEmpty(result)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            }else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), result);
            }
        } catch (Exception ex) {
            log.info("撤销推送NC数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE);
        }
    }
    @ApiOperation("获取NC凭证号")
    @PostMapping("getNcVoucherNo")
    @ResponseBody
    public ObjectDataResponse getNcVoucherNo(@RequestBody Map<String, Object> params) {
        tblNcVurcherDetailPlusService.updateNcVoucherNo(params);
        return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
    }

    @ApiOperation("附件归集")
    @PostMapping("annexCol")
    @ResponseBody
    public ObjectDataResponse annexCol(@RequestBody Map<String, Object> params) {
        tblNcVurcherDetailPlusService.annexCol(params);
        return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
    }

    @Override
    protected List<TblNcVurcherDetailPlus> getExportDate(Map<String, Object> params) throws ServiceException {
        setParamsModel(params);
        Map<String,Long> map = new HashMap<>(16);
        String vn = (String) params.get("startVurcherNumber");
        Long startVurcherNumber = null;
        if(StringUtils.isNotEmpty(vn)){
            startVurcherNumber = Long.parseLong(vn);
        }
        List<TblNcVurcherDetailPlus> list = super.getExportDate(params);
        if(startVurcherNumber!=null){
            String preSummaryIn = null;
            Long vurchurNumber = startVurcherNumber;
            for (TblNcVurcherDetailPlus summary: list ) {
                String summaryIn = summary.getSummary();
                if(summaryIn == null){
                    summaryIn = "";
                }
                if(!StringUtils.isEmpty(summaryIn)){
                    summaryIn = summaryIn.split("/")[1];
                }

                if(!summaryIn.equals(preSummaryIn)&& !map.containsKey(summaryIn)) {
                    if(preSummaryIn!=null){
                        vurchurNumber++;
                    }
                    map.put(summaryIn,vurchurNumber);
                }

                summary.setVurcherNumber(map.get(summaryIn)+"");
                preSummaryIn = summaryIn;
            }
        }
        return list;
    }

    @Override
    public void exportExcelPost(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> params) throws Exception {
        setParamsModel(params);
        String fileName = "NC凭证明细-导出数据.xlsx";
        String path = exportRootPath + System.currentTimeMillis() + File.separator;
        CsvExportUtil.createCsv()
                .headClass(TblNcVurcherDetailPlusExportData.class)
                .fileName(fileName)
                .fileType(ExcelFileType.XLSX)
                .model(CsvExportBuilder.SINGLE_MODEL)
                .parentPath(path)
                .csvDatas(new DateSpiltCsvDatas(tblNcVurcherDetailPlusService, params))
                .export(request, response);
    }
}

